import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  List, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Tabs,
  Image,
  Row,
  Col
} from 'antd';
import { 
  MessageOutlined, 
  PlusOutlined, 
  SearchOutlined,
  EyeOutlined,
  LikeOutlined,
  CommentOutlined,
  ClockCircleOutlined,
  PictureOutlined
} from '@ant-design/icons';
import { Post } from '../../types';
import './Discussion.scss';

const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Discussion: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [posts, setPosts] = useState<Post[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [sortBy, setSortBy] = useState('latest');
  const [activeTab, setActiveTab] = useState('all');

  // 模拟讨论数据
  const mockPosts: Post[] = [
    {
      id: '1',
      title: '期末考试复习方法分享',
      content: '马上就要期末考试了，分享一下我的复习方法，希望对大家有帮助。首先制定详细的复习计划，然后按科目分类复习...',
      author: { id: '1', username: '学霸小王', email: 'xiaowang@example.com', role: 'student' },
      category: 'discussion',
      tags: ['学习', '考试', '复习方法'],
      createdAt: '2024-01-15T10:30:00Z',
      updatedAt: '2024-01-15T10:30:00Z',
      likes: 45,
      comments: 23,
      views: 256,
    },
    {
      id: '2',
      title: '今天食堂的饭菜真不错',
      content: '今天中午在食堂吃到了很好吃的红烧肉，推荐大家去试试！',
      author: { id: '2', username: '美食达人', email: 'meishi@example.com', role: 'student' },
      category: 'discussion',
      tags: ['日常', '食堂', '美食'],
      createdAt: '2024-01-15T09:15:00Z',
      updatedAt: '2024-01-15T09:15:00Z',
      likes: 12,
      comments: 8,
      views: 89,
    },
    {
      id: '3',
      title: '吐槽一下学校的网络',
      content: '学校的网络真的太慢了，看个视频都要缓冲半天，什么时候能升级一下网络设备啊...',
      author: { id: '3', username: '网络受害者', email: 'wangluo@example.com', role: 'student' },
      category: 'discussion',
      tags: ['吐槽', '网络', '校园'],
      createdAt: '2024-01-15T08:45:00Z',
      updatedAt: '2024-01-15T08:45:00Z',
      likes: 28,
      comments: 15,
      views: 134,
    },
    {
      id: '4',
      title: 'React Hooks 使用心得',
      content: '最近在学习React Hooks，发现useEffect的使用有很多细节需要注意，分享一下我的学习心得...',
      author: { id: '4', username: '前端新手', email: 'frontend@example.com', role: 'student' },
      category: 'discussion',
      tags: ['学习', 'React', '前端'],
      createdAt: '2024-01-14T16:30:00Z',
      updatedAt: '2024-01-14T16:30:00Z',
      likes: 34,
      comments: 18,
      views: 189,
    },
    {
      id: '5',
      title: '周末去哪里玩比较好？',
      content: '这个周末想出去放松一下，大家有什么推荐的地方吗？最好是离学校比较近的...',
      author: { id: '5', username: '周末达人', email: 'weekend@example.com', role: 'student' },
      category: 'discussion',
      tags: ['日常', '娱乐', '推荐'],
      createdAt: '2024-01-14T14:20:00Z',
      updatedAt: '2024-01-14T14:20:00Z',
      likes: 18,
      comments: 12,
      views: 98,
    },
  ];

  const subCategories = [
    { key: 'all', label: '全部讨论' },
    { key: 'study', label: '学习' },
    { key: 'daily', label: '日常' },
    { key: 'complain', label: '吐槽' },
  ];

  useEffect(() => {
    loadPosts();
  }, [currentPage, searchKeyword, sortBy, activeTab]);

  const loadPosts = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredPosts = mockPosts;
      
      // 按子分类过滤
      if (activeTab !== 'all') {
        filteredPosts = mockPosts.filter(post => {
          const firstTag = post.tags[0];
          switch (activeTab) {
            case 'study':
              return firstTag === '学习' || firstTag === '考试' || firstTag === 'React';
            case 'daily':
              return firstTag === '日常' || firstTag === '食堂' || firstTag === '娱乐';
            case 'complain':
              return firstTag === '吐槽' || firstTag === '网络';
            default:
              return true;
          }
        });
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredPosts = filteredPosts.filter(post => 
          post.title.includes(searchKeyword) || 
          post.content.includes(searchKeyword) ||
          post.tags.some(tag => tag.includes(searchKeyword))
        );
      }
      
      // 排序
      filteredPosts.sort((a, b) => {
        switch (sortBy) {
          case 'latest':
            return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          case 'popular':
            return b.views - a.views;
          case 'likes':
            return b.likes - a.likes;
          case 'comments':
            return b.comments - a.comments;
          default:
            return 0;
        }
      });
      
      setPosts(filteredPosts);
      setTotal(filteredPosts.length);
    } catch (error) {
      console.error('加载讨论失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handlePostClick = (postId: string) => {
    navigate(`/posts/discussion/${postId}`);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
    setCurrentPage(1);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const getSubCategoryColor = (tag: string) => {
    const colors = {
      '学习': 'blue',
      '日常': 'green',
      '吐槽': 'red',
      '考试': 'purple',
      'React': 'cyan',
    };
    return colors[tag as keyof typeof colors] || 'default';
  };

  return (
    <div className="discussion-page">
      <div className="page-header">
        <div className="header-left">
          <h1>讨论区</h1>
          <p>分享想法，交流观点，畅所欲言</p>
        </div>
      </div>

      {/* 子分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={subCategories.map(cat => ({
            key: cat.key,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索讨论内容..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
            >
              <Option value="latest">最新发布</Option>
              <Option value="popular">最多浏览</Option>
              <Option value="likes">最多点赞</Option>
              <Option value="comments">最多评论</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 讨论列表 */}
      <Card className="posts-card">
        <Spin spinning={loading}>
          {posts.length > 0 ? (
            <List
              dataSource={posts}
              renderItem={(post) => (
                <List.Item
                  className="post-item"
                  onClick={() => handlePostClick(post.id)}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<MessageOutlined />} />}
                    title={
                      <div className="post-title">
                        <span>{post.title}</span>
                        <Tag color={getSubCategoryColor(post.tags[0])}>
                          {post.tags[0]}
                        </Tag>
                      </div>
                    }
                    description={
                      <div className="post-content">
                        <div className="post-text">
                          <p>{post.content}</p>
                        </div>
                        
                        <div className="post-tags">
                          {post.tags.map((tag, index) => (
                            <Tag key={index} size="small" color={getSubCategoryColor(tag)}>
                              {tag}
                            </Tag>
                          ))}
                        </div>
                        
                        <div className="post-meta">
                          <div className="post-author">
                            <span>作者：{post.author.username}</span>
                            <span className="post-time">
                              <ClockCircleOutlined /> {formatDate(post.createdAt)}
                            </span>
                          </div>
                          <div className="post-stats">
                            <span><EyeOutlined /> {post.views}</span>
                            <span><LikeOutlined /> {post.likes}</span>
                            <span><CommentOutlined /> {post.comments}</span>
                          </div>
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty 
              description="暂无讨论内容"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {total > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={10}
              onChange={setCurrentPage}
              showSizeChanger={false}
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Discussion;
